package com.diandian.service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.diandian.orc.baidu.OCRUtil;
import com.diandian.util.StringUtil;
import com.diandian.util.VerbalAssociation;
import com.diandian.vo.Product;

/**
 * @description BaiduOcrService
 * @author TDW
 * @date 2018年8月10日
 *
 */
public class BaiduOcrService {
	private static final Logger log = LoggerFactory.getLogger(BaiduOcrService.class);
	
	
	public static ArrayList<Product> getProducts(String[] template,String filePath){
		ArrayList<Product> products = new ArrayList<Product>();
		long startTime = System.currentTimeMillis();
		JSONObject result = OCRUtil.parseImg(filePath);
		log.info("baidu解析的结果为：{}"+result);
		log.info("文字解析耗时：" + String.valueOf( System.currentTimeMillis() - startTime) + "ms");
		JSONArray jsonArray = result.getJSONArray("words_result");
		if (jsonArray == null) {
			return products;
		}
		
		template = new String[] { "菜品名", "菜品价格" };
		Map<String, String> productMap = getProducts(template, jsonArray);
		if(productMap == null || productMap.isEmpty())
			return products;
		
		Product product = null;
		for(Entry<String, String> entry : productMap.entrySet()){
			product = new Product();
			if(StringUtil.isBlank(entry.getValue())){
				product.setItemName(entry.getKey());
				product.setMemo("【"+entry.getKey()+"】可能是分类，或菜品价格丢失");
			}else{
				product.setProductName(entry.getKey());
				product.setPrice(Double.parseDouble(entry.getValue()));
				product.setMemo("ok");
			}
			products.add(0,product);
		}
		return products;
	}
	
	
	public static ArrayList<Product> getProducts(String[] template,String[] filePaths){
		
		ArrayList<Product> products = new ArrayList<Product>();
		for(String filePath : filePaths){
			long startTime = System.currentTimeMillis();
			JSONObject result = OCRUtil.parseImg(filePath);
			log.info("baidu解析的结果为：{}"+result);
			log.info("文字解析耗时：" + String.valueOf( System.currentTimeMillis() - startTime) + "ms");
			JSONArray jsonArray = result.getJSONArray("words_result");
			if (jsonArray == null) {
				return products;
			}
			template = new String[] { "菜品名", "菜品价格" };
			Map<String, String> productMap = getProducts(template, jsonArray);
			if(productMap == null || productMap.isEmpty())
				return products;
			
			Product product = null;
			for(Entry<String, String> entry : productMap.entrySet()){
				product = new Product();
				if(StringUtil.isBlank(entry.getValue())){
					product.setItemName(entry.getKey());
					product.setMemo("【"+entry.getKey()+"】可能是分类，或菜品价格丢失");
				}else{
					product.setProductName(entry.getKey());
					product.setPrice(Double.parseDouble(entry.getKey()));
					product.setMemo("ok");
				}
				products.add(0,product);
			}
		}
		return products;
	}
	
	
	
	
	/**
	 * 解析菜品
	 */
	public static Map<String, String> getProducts(String[] template, JSONArray jsonArray) {
		// parse product
		// productnamexxx元（圆）
		// productname
		// XXX元（圆）
		// productname（辣）xxx元（圆）..
		// parse 1
		// 输入模板
		
		Map<String, String> products = new LinkedHashMap<String, String>();
		for (int i = 0; i < jsonArray.length(); i++) {
			if (i >= jsonArray.length())
				break;
			try {
				if ("菜品名".equals(template[0]) && "菜品价格".equals(template[1])) {
					JSONObject json = (JSONObject) jsonArray.get(i);

					String element = json.getString("words");
					element = StringUtil.getRightfulStr(element);
					element = VerbalAssociation.replaceErrWord(element);
					element = VerbalAssociation.cutFirstWord(element);

					log.info("开始解析：" + element);
					int eleIndex = getMoneyMarkIndex(element);
					// 此情况可能是分类，也可能是 菜品名\n菜品价格
					if (eleIndex == -1 && i < jsonArray.length()) {
						// next element
						String[] producInfo = StringUtil.getStrLastNum(element);
						if(producInfo.length == 2){
							products.put(producInfo[0], producInfo[1]);
							continue;
						}
							

						String nextElement = ((JSONObject) jsonArray.get(i + 1)).getString("words");
						nextElement = StringUtil.getRightfulStr(nextElement);
						int nextEleIndex = getMoneyMarkIndex(nextElement);
						if (nextEleIndex == -1) {// 认为是分类
							
							nextElement = nextElement.trim();
							//纯数字也可能是上个元素的菜的价格
							Double price = 0d;
							try{
								price = Double.parseDouble(nextElement);
							}catch(Exception e){
								// log
							}
							if(price>0){
								products.put(element, nextElement);
								i++;
								continue;
							}
							
							log.info("【" + element + "】应该是分类名");
							products.put(element, null);
							continue;
						} else {
							if (nextElement.length() <= 5) {// 认为是菜品
								String price = getPrice(nextEleIndex, nextElement).split("#")[0];
								products.put(element, price);
								i++;
								continue;
							} else {
								// 没有价格标签，并且下一个元素含有价格标签，并且下一个标签的长度>6
								log.info("【" + element + "】应该是分类名");
								products.put(element, null);
								continue;
							}
						}
					}
					String priceStr = getPrice(eleIndex, element);
					String[] priceArr = priceStr.split("#");
					if(priceArr.length>=2){
						System.out.println(element+"=="+priceArr[0]+"="+priceArr[1]);
						String productName = element.substring(0, Integer.parseInt(priceArr[1]) + 1);
						products.put(productName, priceArr[0]);
					}
					System.out.println(element);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return products;
	}

	/**
	 * @description getMoneyMarkIndex 钱单位库
	 * @param element
	 * @return
	 * @author TDW
	 * @date 2018年8月11日
	 * @modify_date 
	 * @modify_author
	 * @modify_desc
	 */
	private static int getMoneyMarkIndex(String element) {
		String[] priceMark = {"元","圆","￥","亓","无","圥","兀","几","用","圎","圓","園","园","份"};
		int yuanIndex = -1;
		for(String mark : priceMark){
			yuanIndex = element.lastIndexOf(mark);
			if(yuanIndex >= 0)
				return yuanIndex;
		}
		return yuanIndex;
	}
	
	

	private static String getPrice(int yuanIndex, String element) {
		StringBuffer priceBuff = new StringBuffer(5);
		element = element.substring(0, yuanIndex);
		char[] chars = element.toCharArray();
		int j=0;
		for (int i = chars.length - 1; i > -1; i--) {
			char chr = chars[i];
			if (Character.isDigit(chr) || chr == 46) {
				priceBuff.insert(0, chr);
			} else {
				priceBuff.append("#").append(i);
				break;
			}
			//j=i;

		}
//		if(priceBuff.indexOf("#") == -1)
//			priceBuff.append("#").append(j);
		System.out.println("priceBuff="+priceBuff);
		return priceBuff.toString();
	}

	private String getContext(HttpServletRequest request) {
		String result = "";
		try {
			result = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
